<?php

class RestaurantsController extends Controller {

	public $seo_default = 'Рестораны';
	public $seo = '';
	public $baseUrl = '';
	public $cats = array();
	public $bread;

	public function init() {
		$this->cats = Category::model()->findAll();
		$this->baseUrl = Yii::app()->request->baseUrl;
	}
	public function actionIndex() {

		$data['category_id'] = Yii::app()->request->getParam('category_id');
		$this->bread = array(
			'Рестораны'
		);
		if( $data['category_id'] == '' ) {
			$data['category'] = Category::model()->findAll();
			$data['categories_restaurants'] = CategoryRestaurant::model()->findAll(array(
				'select'=>'t.id_restaurant',
				'distinct'=>true,
			));
		} else {
			$data['category'] = Category::model()->findByPk($data['category_id']);
			$data['categories_restaurants'] = CategoryRestaurant::model()->findAllByAttributes(array('id_category'=>$data['category_id']));
		}
		$this->render('index',$data);
	}
	public function actionGetRestaurants() {
		$data = $rests = $condition = $with = array();
		$req = Yii::app()->request;
		if( $_p = $req->getPost('data') ) {
			$view_type = $_p['view_type'];
			$criteria = isset($_p['criteria']) ? $_p['criteria'] : '';

			switch( $criteria ) {
				case 'free_shipping':
					$condition[] = 'delivery=0';
					break;
				case 'actions':
					$with['actions'] = array('condition' => '`actions`.`isVisible`=1');
					break;
				case 'no_cash':
					//TODO: добавить поле в таблицу ресторанов, принимают ли они безнал или нет, только потом здесь что-то делать
					//$condition[] = '';
					break;
			}
			$db_criteria = new CDbCriteria();
			if( !empty($condition) ) {
				$db_criteria->condition = implode(' AND ',$condition);
			}
			if( !empty($_p['cats']) && is_array($_p['cats']) ) {
				$with['categoryRestaurants'] = array(
					'condition' => '`categoryRestaurants`.`id_category` IN ('.implode(',',$_p['cats']).')',
					'together'=>true
				);
			}
			if( !empty($with) ) {
				$db_criteria->with = $with;
			}
			$rests = Restaurants::model()->findAll($db_criteria);
			$data['html'] = '';
			if( $view_type == 'list' ) {
				foreach( $rests as $rest ) {
					$data['html'] .= $this->renderPartial('//restaurants/restaurant_list',array('rest'=>$rest),true);
				}
			} else {
				$data['html'] .= $this->renderPartial('//restaurants/restaurant_grid',array('rests'=>$rests),true);
			}
		}
		$data['data'] = $_p;
		echo json_encode($data);
		Yii::app()->end();
	}
}